/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.funda.xmppserver.x;

import com.funda.xmppserver.XMPPClient;
import com.funda.xmppserver.XMPPInfo;
import com.funda.xmppserver.mysql.DBManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author srkrishnan
 */
public class XDelay {

    XMPPClient client;
    Connection conn;
    Statement smt;
    ResultSet rs;

    public XDelay(XMPPClient client) {
        this.client = client;
        conn = DBManager.getConn();

    }

    public void checkXDelaymsg() {
        try {
            smt = conn.createStatement();
            rs = smt.executeQuery("select * from chathistory where toid='" + (client.getUsername() + "@" + XMPPInfo.getHOST()) + "' and delay=1");

            while (rs.next()) {
                System.out.println(rs.getString("id") + ":" + rs.getString("fromid") + ":" + rs.getString("fromjid") + ":" + rs.getString("fromid") + ":" + rs.getString("msg"));

                Calendar cal = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'hh:mm:ss");
                System.out.println(sdf.format(cal.getTime()));
                client.getPacketwriter().sendXDelayMsg(rs.getString("fromid"),rs.getString("msg"), rs.getString("timestamp"));

                PreparedStatement prpsmt = conn.prepareStatement("update chathistory set delay=0,deliveredtime='"+sdf.format(cal.getTime())+"' where id=" + rs.getInt("id"));
                int c = prpsmt.executeUpdate();
                System.out.println("" + c + " row(s) updated successfully!!");

                Thread.sleep(100);
            }

        } catch (InterruptedException ex) {
            Logger.getLogger(XDelay.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(XDelay.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}
